package net.tuura.demo.snippet
  
import scala.xml.NodeSeq
import net.liftweb.util._
import net.liftweb.common._
import net.tuura.demo.lib._
import net.tuura.demo.model._
import net.liftweb.http.S
import net.liftweb.http.SHtml
import Helpers._

class TuuraDemo {
      
  def listProblems (xhtml:NodeSeq) : NodeSeq = {
    Problem.findAll.flatMap (
      p => bind ("p", xhtml,
                 "name" -> p.name,
                 "author" -> p.author,
                 "lang" -> p.language
      )
    )
  }

  def addProblem (xhtml:NodeSeq) : NodeSeq = {
    var name = "A very hard problem"
    var statement = "Who is to blame and what to do?"
    var refSolution = "abcdefghjkl"
    var refSolutionLang = "C++"

    def processProblem() = {
      val p = Problem.create
      p.name(name)
      p.author(User.currentUser.open_!.niceName)
      p.language(refSolutionLang)
      p.save() 

      S.redirectTo("/index")
    }


    if (User.loggedIn_?)
      bind ( "problem", xhtml,
            "name" -> SHtml.text(name, x => name = x),
            "statement" -> SHtml.textarea(statement, x => statement = x),
            "refSolution" -> SHtml.textarea(refSolution, x => refSolution = x),
            "refSolutionLang" -> SHtml.select(List("C++", "Java", "Haskell", "Whatever").map(x=>(x,x)), Empty , x => refSolutionLang = x),
            "submit" -> SHtml.submit("Add problem", processProblem)
      )
    else
      <p>Please log in to add problems</p>

  }

}
